package com.anjubao.parking.municipal.user.service;

import com.anjubao.parking.municipal.user.constants.BalanceTypeEnum;
import com.anjubao.parking.municipal.user.dto.UserBalanceRecordDto;
import com.anjubao.parking.municipal.user.mapper.UserBalanceRecordMapper;
import com.anjubao.parking.municipal.user.model.UserBalanceRecord;
import com.anjubao.parking.municipal.user.utils.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户余额变动记录Service
 *
 * @author zhuchunfeng
 */
@Service
public class UserBalanceRecordService {

    @Resource
    private UserBalanceRecordMapper userBalanceRecordMapper;

    /**
     * 获取用户充值记录
     *
     * @param userCode 用户编号
     * @param type     1-充值 2消费
     * @param page     页码
     * @param pageSize 页大小
     * @return 页码
     */
    public IPage<UserBalanceRecordDto> getUserBalanceRecords(String userCode, Integer type, Integer page, Integer pageSize) {
        return userBalanceRecordMapper.selectPage(
                new Page<>(page, pageSize),
                new QueryWrapper<>(
                        new UserBalanceRecord().setUserId(IdUtil.getId(userCode))
                ).lambda()
                        .eq(BalanceTypeEnum.exist(type), UserBalanceRecord::getType, type)
                        .orderByDesc(UserBalanceRecord::getCreateTime)
        ).convert(r -> {
            UserBalanceRecordDto u = new UserBalanceRecordDto();
            u.setUserCode(IdUtil.getCode(r.getUserId()));
            u.setType(r.getType());
            u.setAmount(r.getAmount());
            u.setRemark(r.getRemark());
            u.setCreateTime(r.getCreateTime());
            u.setTradeOrderId(r.getTradeOrderId());
            return u;
        });

        //按前段要求返回数据
//        List<UserBalanceRecordDto> records = recordPage.getRecords();
//        Map<String, List<UserBalanceRecordDto>> collect = records.stream().collect(Collectors.groupingBy(t -> t.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM"))));

//        return ApiResult.success(collect, (int) recordPage.getTotal());
    }
}
